package com.example.vertification.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.Utils.Utils;
import com.example.vertification.entity.ChatMessage;
import com.example.vertification.entity.User;
import com.example.vertification.repository.ChatRepository;
import com.example.vertification.service.ChatMessageService;
import com.example.vertification.service.RegisterCodeService;
import com.example.vertification.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@Api(value = "聊天通信", tags = "聊天发包API")
public class ChatController {

    private final UserService userService;
    private final ChatMessageService cms;

    @Autowired
    public ChatController(UserService userService, ChatMessageService cms) {
        this.userService = userService;
        this.cms = cms;
    }

    @ApiOperation(value = "通过token，发送给对应的人uid，内容")
    @GetMapping("/send_msg")
    public ResponseEntity<?> send_msg(String token,String uid,String content,HttpServletRequest request) {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登录");
        }
        ChatMessage cm = new ChatMessage(u.getUid(),Long.parseLong(uid),content,new Date().getTime(), ChatMessage.MessageStatus.SENT,Utils.getIpByServerlet(request));
        cms.createChatMessage(cm);
        return ResponseEntity.ok("success");
    }



    @ApiOperation(value = "通过token，对象的UID,进行已读设置")
    @GetMapping("/has_read_uid")
    public ResponseEntity<?> has_read_uid(String token,String uid,HttpServletRequest request) {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登录");
        }
        List<ChatMessage> ls = cms.getContent(uid,String.valueOf(u.getUid()));

        for(ChatMessage cm: ls){
            cm.setStatus(ChatMessage.MessageStatus.READ);
            cms.SaveMessage(cm);
        }
        return ResponseEntity.ok("success");
    }


    @ApiOperation(value = "通过token，获得与我有关的聊天数组")
    @GetMapping("/get_relate_with_me")
    public ResponseEntity<?> get_relate_with_me(String token,HttpServletRequest request) {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登录");
        }

        List<ChatMessage> lcms1 =  cms.findBySenderUid(String.valueOf(u.getUid()));
        List<ChatMessage> lcms2 =  cms.findByReceiverUid(String.valueOf(u.getUid()));
        List<ChatMessage> mergedList = new ArrayList<>(lcms1);
        mergedList.addAll(lcms2);



        // 步骤1: 提取唯一联系人列表
        Map<String, List<Map<String, Object>>> contactMessagesMap = new HashMap<>();
        for (ChatMessage cm : mergedList) {
            String sender = String.valueOf(cm.getSenderUid());
            String receiver = String.valueOf(cm.getReceiverUid());

            // 假设我们只关心与当前用户的聊天记录，这里使用receiver作为唯一标识
            String partner = String.valueOf(cm.getSenderUid()).equals(String.valueOf(u.getUid())) ? receiver : sender;

            // 创建聊天记录的Map对象
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("content", cm.getMessageContent());
            messageMap.put("timestamp", cm.getSendTime());
            messageMap.put("sender", String.valueOf(cm.getSenderUid()).equals(String.valueOf(u.getUid())) ? "Me" : "Contact");
            messageMap.put("isRead", cm.getStatus() == ChatMessage.MessageStatus.SENT ? false:true);
            // 将聊天记录添加到对应联系人的列表中
            contactMessagesMap.computeIfAbsent(partner, k -> new ArrayList<>()).add(messageMap);
        }

        // 步骤2: 构建每个联系人的信息，包括其所有聊天记录
        List<Map<String, Object>> recentContacts = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, Object>>> entry : contactMessagesMap.entrySet()) {
            // 提取最后一条聊天记录的时间用于排序
            long latestTimestamp = entry.getValue().stream()
                    .mapToLong(msg -> (Long) msg.get("timestamp"))
                    .max()
                    .orElse(0L);


            long unreadCount = entry.getValue().stream()
                    .filter(msg -> !(Boolean) msg.get("isRead") && !(msg.get("sender").toString().equalsIgnoreCase("Me"))) // 过滤出未读消息
                    .count();

            // 创建联系人的Map对象，包含UID和最后聊天时间
            Map<String, Object> contactMap = new HashMap<>();
            User temp_u = userService.getUserByUId(Long.valueOf(entry.getKey()));
            if(temp_u==null){
                continue;
            }
            temp_u.setPassword("*********");
            contactMap.put("uid", JSONUtil.parseObj(temp_u));
            contactMap.put("latestTimestamp", latestTimestamp);
            contactMap.put("messages", entry.getValue()); // 所有聊天记录
            contactMap.put("unreadCount", unreadCount); // 添加未读消息计数
            // 添加到联系人列表中
            recentContacts.add(contactMap);
        }

        // 步骤3: 根据最后聊天时间排序联系人列表（降序）
        recentContacts.sort((c1, c2) -> Long.compare((Long) c2.get("latestTimestamp"), (Long) c1.get("latestTimestamp")));

        // 步骤4: 返回给前端（这里转换为JSONObject是为了演示，实际中可能直接返回List<Map<String, Object>>）
        JSONArray jsonArray = new JSONArray();
        for (Map<String, Object> contact : recentContacts) {
            jsonArray.add(new JSONObject(contact));
        }
        return ResponseEntity.ok(jsonArray);
    }


}
